#include <iostream>
#include <string>
#include <unistd.h>
#include <time.h>
#include <cassert>
#include "Sockets.hpp"
#include "Protocol.hpp"

using namespace std;

static void Usage(const std::string &proc)
{
    cout << "\nUsage: " << proc << " serverip serverport\n" << endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    Sockets sockets;
    sockets.Socket();
    bool r = sockets.Connect(serverip, serverport);
    if(!r)
        return 1;
    
    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    const std::string opers = "+-*/%=&^|";

    string inbuffer_stream;
    while(cnt <= 10)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char oper = opers[rand()%opers.size()];
        Request req(x, y, oper);
        req.DebugPrint();

        string package;
        req.Serialize(package);
        package = Encode(package);

        std::cout << "这是最新的发出去的请求: " << "\n" << package;
        write(sockets.Fd(), package.c_str(), package.size());

        char buffer[128];
        ssize_t n = read(sockets.Fd(), buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            cout << inbuffer_stream << endl;
            string content;
            bool r = Decode(inbuffer_stream, content);
            assert(r);

            Response resp;
            r = resp.Deserialize(content);
            assert(r);

            resp.DebugPrint();
        }

        cout << "=================================================" << endl;
        sleep(1);
        cnt++;
    }

    sockets.Close();
    return 0;
}